﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.DataVisualization.Charting;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class Player : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                this.PlayerBidFormView.Visible = false;
            
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            //this.Title = GND.ReturnAppTitle();
            
            bool ForSale, IsOwner, IsPendingTransfer;
            string NationalTeamId;

            string PlayerId = null;
            if (Request.QueryString["Id"] != null)
            {
                PlayerId = Request.QueryString["Id"].ToString();
                this.PlayerIdHiddenField.Value = Request.QueryString["Id"].ToString();
            }
            if (PlayerId == null)
                Response.Redirect("~/Default.aspx");

            if (Request.QueryString["Message"] != null)
            {
                this.ErrorLabel.Text = Request.QueryString["Message"];
                this.ErrorLabelPanel.Visible = true;
            }
            
            if (ou.TeamId != "Null")
                this.TeamIdHiddenField.Value = ou.TeamId;


            if (ou.IsPremium)
                IsPremiumHiddenField.Value = "true";
            else
                IsPremiumHiddenField.Value = "false";

            IsOwner = GND.ReadNivdalBoolData("PlayerId", "UserId", "Nivdal_IsUserPlayersOwner", PlayerId, ou.UserId);
            ForSale = GND.ReadNivdalBoolData("@PlayerId", "Nivdal_IsPlayerForSale", PlayerId);
            IsPendingTransfer = GND.ReadNivdalBoolData("PlayerId", "Nivdal_IsPlayerPendingTransfer", PlayerId);
            NationalTeamId = GND.ReadNivdalIntData("PlayerId", "Nivdal_NTdoesPlayerBelongToNationalTeamProc", PlayerId);


            if (!IsPostBack)
            {

                this.PlayerDetailsSqlDataSource.SelectParameters.Add("PlayerId", PlayerId);
                this.PlayerDetailsSqlDataSource.SelectParameters.Add("Language", ou.Language);
                this.PlayerMatchesDataSourse.SelectParameters.Add("PlayerId", PlayerId);
                this.PlayerMatchesDataSourse.SelectParameters.Add("Language", ou.Language);
                this.PlayerBidSqlDataSource.SelectParameters.Add("PlayerId", PlayerId);
                this.PlayerBidSqlDataSource.SelectParameters.Add("Language", ou.Language);
                this.TrainingReportsDataSourse.SelectParameters.Add("PlayerId", PlayerId);
                this.TrainingReportsDataSourse.SelectParameters.Add("Language", ou.Language);
                this.ConditionalBidDataSource.SelectParameters.Add("PlayerId", PlayerId);
                this.ConditionalBidDataSource.SelectParameters.Add("TeamId", ou.TeamId);
                this.ConditionalBidDataSource.UpdateParameters.Add("TeamId", ou.TeamId);
                this.ConditionalBidDataSource.UpdateParameters.Add("PlayerId", PlayerId);
                this.TransferTimeOptionsSqlDataSource.SelectParameters.Add("Language", ou.Language);
                this.ShirtsDataSourse.SelectParameters.Add("PlayerId", PlayerId);
                this.ShirtsDataSourse.SelectParameters.Add("Language", ou.Language);
                this.BestRatingsDataSource.SelectParameters.Add("PlayerId", PlayerId);
                this.BestRatingsDataSource.SelectParameters.Add("Language", ou.Language);
                this.NTShirtsDataSourse.SelectParameters.Add("PlayerId", PlayerId);
                this.NTShirtsDataSourse.SelectParameters.Add("Language", ou.Language);
                this.TransfersDataSource.SelectParameters.Add("PlayerId", PlayerId);
                this.TransfersDataSource.SelectParameters.Add("Language", ou.Language);
            }

            this.ForSalePanel.Visible = ForSale;
            this.SellPanel.Visible = IsOwner && (!ForSale) && (!IsPendingTransfer);
            this.PendingSalePanel.Visible = (IsOwner && IsPendingTransfer);

            if (NationalTeamId != "0")
            {
                (FormView1.FindControl("NationalTeamLink") as HyperLink).Text = GND.ReadNivdalStringData("NTTeamId", "Nivdal_NTGetNationalTeamNameById", NationalTeamId);
                (FormView1.FindControl("NationalTeamLink") as HyperLink).NavigateUrl = "~/NationalTeam.aspx?Id=" + NationalTeamId;
                
                if (ou.NationalTeamCoach == NationalTeamId)
                {
                    (FormView1.FindControl("NTReleasePanel") as Panel).Visible = true;
                    (FormView1.FindControl("NTPrivateNote") as Panel).Visible = true;
                    (FormView1.FindControl("NTShirtNumPanel") as Panel).Visible = true;                    
                }
            }
            else
            {
                if (GND.ReadNivdalBoolData("UserId", "PlayerId", "Nivdal_NTCanUserInvitePlayerToNationalTeam", ou.UserId, PlayerId))
                {
                    (FormView1.FindControl("NTInvitePanel") as Panel).Visible = true;
                }
                (FormView1.FindControl("IsNationalTeamPlayer") as Panel).Visible = false;
            }
            if (IsOwner)
            {
                //GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                //this.ErrorLabel.Text = (GND.ReadNivdalBoolData("@PlayerId", "Nivdal_HealthDoesPlayerNeedSurgery", PlayerId)).ToString();
                if (GND.ReadNivdalBoolData("@PlayerId", "Nivdal_HealthDoesPlayerNeedSurgery", PlayerId))
                {
                    this.SurgeryPanel.Visible = true;
                    String cost = GND.ReadNivdalIntData("@PlayerId", "Nivdal_HealthCalculateSurgeryCost", PlayerId);
                    this.SurgeryButton.OnClientClick = "if(!confirm('" + Resources.Resource.Player_SureSurgeryButton + " " + cost + " Atuks'))return false;";
                }
                this.PlayerBidFormView.FindControl("CanBidPanel").Visible = false;
                this.PlayerBidFormView.FindControl("ConditionalBidPanel").Visible = false;
                this.TrainingUpdatesPanel.Visible = true;
                if ((ou.IsPremium) && (!IsPostBack))
                {
                    TrainingGraphPanel.Visible = true;
                    RefreshTrainingGraph();
                }
                this.TrainingStringLabel.Text = GND.ReadNivdalStringData("PlayerId", "Language", "Nivdal_GetPlayerTraining", PlayerId, ou.Language);
                (this.FormView1.FindControl("ShirtNumPanel") as Panel).Visible = true;
                (this.FormView1.FindControl("PrivateNotePanel") as Panel).Visible = true;
                (this.FormView1.FindControl("PublicNoteEditPanel") as Panel).Visible = true;
                
            }

            FormView1.FindControl("PrivateAttributesPanel").Visible = IsOwner || ForSale || ((NationalTeamId == ou.NationalTeamCoach) && (ou.NationalTeamCoach != "0"));
            FormView1.FindControl("WageNegPanel").Visible = IsOwner;

            string PlayerName = GND.ReadNivdalStringData("PlayerId", "Nivdal_GetPlayerNameByIdProc", PlayerId);
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.Player_PageTitle + ": " + PlayerName;
            //this.Title = PlayerName + " - nivdal.com!";
            this.PageNameLabel.Text = Resources.Resource.Player_RightPageNameLabel + " " + PlayerName;

        }

        public bool IsPremium()
        {
            return (IsPremiumHiddenField.Value == "true");

        }
        //public bool IsForSale(Object obj)
        //{
        //    if (obj.ToString() == "For sale!")
        //        return false;
        //    else
        //        return true;

        //}

        public bool IsBiddingTeam(Object obj)
        {
            if (obj.ToString() == "No bids yet")
                return false;
            else
                return true;

        }




        //protected void FormView1_OnDataBound(object sender, EventArgs e)
        //{
        //    GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
        //    String PlayerId = PlayerIdHiddenField.Value;
        //    string UserGUID = GND.ReturnUserId();        
        //    if (IsUserShouldSeePlayerDetails())
        //    {
        //        FormView1.FindControl("PrivateAttributesPanel").Visible = false;            
        //        FormView1.FindControl("WageNegPanel").Visible = false;
        //    }        

        //    //if ((IsUserPlayersOwner(UserGUID.ToString(), PlayerId)) || (PremiumHiddenField.Value == "false"))
        //    //{
        //    //    FormView1.FindControl("PrivateNotePanel").Visible = false;
        //    //}        
        //}

        protected void Button1_Click(object sender, EventArgs e)
        {
            String PlayerId = Request.QueryString["Id"].ToString();
            String TransferLength = this.DropDownList1.SelectedValue;
            short ReturnValue = 0;
            string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection
            strConnection = new System.Data.SqlClient.SqlConnection(conn);
            string StrSQL = "Nivdal_CreatePendingTransfer";
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@PlayerId", PlayerId));
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@TransferLength", TransferLength));

            strConnection.Open();
            try
            {
                ReturnValue = Convert.ToInt16(cmd.ExecuteScalar());

                //ErrorLabel.Text = ReturnValue.ToString();
            }
            catch (Exception SQLDBException)
            {
                ErrorLabel.Text = Convert.ToString(SQLDBException);
                this.ErrorLabelPanel.Visible = true;
            }

            finally
            {
                strConnection.Close();
            }
            Response.Redirect("~/Player.aspx?Id=" + PlayerId + "&Message=" + Resources.Resource.Player_PlayerWillBeTransferSoon);
        }

        protected void BookmarkButton_Click(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            String PlayerId = Request.QueryString["Id"].ToString();

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_BookmarkPlayer";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_UserId = new SqlParameter();
            dbParam_UserId.ParameterName = "@UserId";
            dbParam_UserId.Value = ou.UserId;
            dbParam_UserId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_UserId);

            SqlParameter dbParam_BookmarkedPlayer = new SqlParameter();
            dbParam_BookmarkedPlayer.ParameterName = "@BookmarkedPlayer";
            dbParam_BookmarkedPlayer.Value = PlayerId;
            dbParam_BookmarkedPlayer.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_BookmarkedPlayer);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + dbParam_Answer.Value.ToString());
            }
            catch (Exception SQLDBException)
            {
                this.ErrorLabel.Text = Convert.ToString(SQLDBException);
                this.ErrorLabelPanel.Visible = true;
            }

            finally
            {
                dbConnection.Close();
            }

        }

        protected void SurgeryButton_Click(object sender, EventArgs e)
        {
            String PlayerId = Request.QueryString["Id"].ToString();
            string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection
            strConnection = new System.Data.SqlClient.SqlConnection(conn);
            string StrSQL = "Nivdal_HealthDoSurgery";
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@PlayerId", PlayerId));
            strConnection.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception SQLDBException)
            {
                this.ErrorLabel.Text = SQLDBException.Message;
                this.ErrorLabelPanel.Visible = true;
            }

            finally
            {
                strConnection.Close();
            }
            Response.Redirect("~/Player.aspx?Id=" + PlayerId);
        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            String Message = "";
            OnlineUser ou = (OnlineUser)Session["User"];
            String PlayerId = Request.QueryString["Id"].ToString();
            HiddenField NewBidHiddenField = this.PlayerBidFormView.FindControl("NextBidHiddenField") as HiddenField;
            //TextBox NewBidTextBox = (TextBox)this.PlayerBidFormView.FindControl("CurrentBidTextBox");
            String NewBid = NewBidHiddenField.Value;

            //Response.Write(NewBid);
            ///string NewBid = NewBidTextBox.Text.Trim();
            //Response.Write(NewBid);
            ///string returnValue = "error";
            string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection
            strConnection = new System.Data.SqlClient.SqlConnection(conn);
            string StrSQL = "Nivdal_BidOnTransferlistedPlayer";
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@PlayerId", PlayerId));
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@BiddingUser ", ou.UserId)); //The current user id that connecting
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@BidSum ", NewBid)); //take from the next bid label
            strConnection.Open();
            try
            {
                Message = Convert.ToString(cmd.ExecuteScalar());
                // Label5.Text = Convert.ToString(cmd.ExecuteScalar());
                //MessageLabel.Text = "The news was added!";
                ///Response.Redirect("BidOnPlayer.aspx?PlayerId");
            }
            catch (Exception SQLDBException)
            {
                Response.Write(Convert.ToString(SQLDBException));
                //return;

            }

            finally
            {
                strConnection.Close();
            }
            Response.Redirect("~/Player.aspx?Id=" + PlayerId + "&Message=" + Message);
            // Response.Redirect("~/BidOnPlayer.aspx?Id=" + PlayerId );
            //Nivdal_BidOnTransferlistedPlayer
        }

        protected string BidOnPlayerButtonOnClientClick(string Cost)
        {
            return ("return confirm('" + Resources.Resource.Player_OnBidButtonAreYouSurePart1 + " " + Cost +
                   " " + Resources.Resource.Player_OnBidButtonAreYouSurePart2 + "')");

        }

        protected void ConditionalBidCommand(object sender, FormViewCommandEventArgs e)
        {
            string Message = "";
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            if (e.CommandName == "Delete")
            {
                GND.ExecNivdalSQL("ConditionalBidId", "Nivdal_RemoveConditionalBid", e.CommandArgument);
                Message = Resources.Resource.Player_ConditionalBidDeletedText ;
            }
            if (e.CommandName == "Update")
            {
                FormView CondBidFormView = this.PlayerBidFormView.FindControl("ConditionalBidFormView") as FormView;
                TextBox BidTextBox = CondBidFormView.FindControl("ConditionalBidTextBox") as TextBox;
                string CondBid = BidTextBox.Text;
                Message = GND.ReadNivdalStringData("PlayerId", "TeamId", "ConditionalBidSum", "Language", "Nivdal_AddConditionalBidOnPlayer",
                                        this.PlayerIdHiddenField.Value, ou.TeamId, CondBid, ou.Language);
            }

            Response.Redirect("Player.aspx?Id=" + this.PlayerIdHiddenField.Value + "&Message=" + Message);
        }

        protected void RefeshTimerTick(object sender, EventArgs e)
        {
            if (this.ForSalePanel.Visible)
            {
                bool CanBid = this.PlayerBidFormView.FindControl("CanBidPanel").Visible;
                bool CondBidVisible = this.PlayerBidFormView.FindControl("ConditionalBidPanel").Visible;
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                if (!GND.ReadNivdalBoolData("@PlayerId", "Nivdal_IsPlayerForSale", PlayerIdHiddenField.Value))
                {
                    this.ForSalePanel.Visible = false;
                }
                else
                {
                    try
                    {
                        PlayerBidFormView.DataBind();
                        FormView ConditionalBidFormView = PlayerBidFormView.FindControl("ConditionalBidFormView") as FormView;
                        ConditionalBidFormView.DataBind();
                        this.PlayerBidFormView.FindControl("CanBidPanel").Visible = CanBid;
                        this.PlayerBidFormView.FindControl("ConditionalBidPanel").Visible = CondBidVisible;
                    }
                    catch { }
                }
            }
        }

        protected void CancelTransfer(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string Message = GND.ReadNivdalStringData("PlayerId", "Nivdal_DeletePendingTransfer", PlayerIdHiddenField.Value);
            Response.Redirect("Player.aspx?Id=" + this.PlayerIdHiddenField.Value + "&Message=" + Message);
        }


        protected string FormatNumber(object str)
        {
            string ReturnValue = "";
            try
            {
                ReturnValue = Int32.Parse(str.ToString()).ToString("N0");
            }
            catch
            {
                ReturnValue = str.ToString();
            }
            return (ReturnValue);
        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        protected void SetShirtNumButtonClick(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string Answer = GND.ReadNivdalStringData("PlayerId", "ShirtNumber", "Nivdal_SetPlayerShirtNumber", PlayerIdHiddenField.Value,
                                                     (FormView1.FindControl("ShirtsDDL") as DropDownList).SelectedValue);
            Response.Redirect("Player.aspx?Id=" + PlayerIdHiddenField.Value + "&Message=" + Answer);
        }

        protected void SetNTShirtNumButtonClick(object sender, EventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"]; 
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string ShirtNum = (FormView1.FindControl("NTShirtNumDDL") as DropDownList).SelectedValue;
            string Answer = GND.ReadNivdalStringData("PlayerId", "ShirtNumber", "Language",  "Nivdal_SetNTPlayerShirtNumber", PlayerIdHiddenField.Value, ShirtNum, ou.Language);
            Response.Redirect("Player.aspx?Id=" + PlayerIdHiddenField.Value + "&Message=" + Answer);
        }

        protected void SubmitPrivateNote(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string PrivateNote = (FormView1.FindControl("PrivateNoteTextBox") as TextBox).Text.Trim();
            GND.ExecNivdalSQL("PlayerId", "Note", "Nivdal_UpdatePlayerPrivateNote", PlayerIdHiddenField.Value, PrivateNote);
            Response.Redirect("Player.aspx?Id=" + PlayerIdHiddenField.Value + "&Message=" + Resources.Resource.Player_PrivateNoteUpdatedMessageText);
        }
        protected void SubmitNTPrivateNote(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string PrivateNote = (FormView1.FindControl("NTPrivateNoteTextBox") as TextBox).Text.Trim();
            string Answer = GND.ReadNivdalStringData("PlayerId", "Note", "Language", "UserId", "Nivdal_UpdatePlayerNTPrivateNote", PlayerIdHiddenField.Value, PrivateNote, ou.Language, ou.UserId);
            Response.Redirect("Player.aspx?Id=" + PlayerIdHiddenField.Value + "&Message=" + Answer);
        }

        protected string InjuryIconName(object Injury)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            return GND.InjuryIconName(Injury);
        }

        protected string GetIconByMatchType(object o)
        {
            string ReturnValue = "~/Images/Icons/";
            //string Type = (string)o;
            int Type;
            try
            {
                Type = Int32.Parse(o.ToString());
            }
            catch
            {
                Type = 0;
            }

            switch (Type)
            {
                case 1:
                    ReturnValue += "LeagueIcon.png";
                    break;
                case 2:
                    ReturnValue += "NationalCupIcon.png";
                    break;
                case 3:
                    ReturnValue += "InternationalCupIcon.png";
                    break;
                default:
                    ReturnValue += "FriendlyIcon.png";
                    break;
            }
            return (ReturnValue);
        }

        protected void CheckAllAttributes(object sender, EventArgs e)
        {
            InstinctsCheckbox.Checked = true;
            GoalkeepingCheckBox.Checked = true;
            PositioningCheckBox.Checked = true;
            StaminaCheckBox.Checked = true;
            TacklingCheckBox.Checked = true;
            PowerCheckBox.Checked = true;
            HeadingCheckBox.Checked = true;
            QuicknessCheckBox.Checked = true;
            TechniqueCheckBox.Checked = true;
            ShootingCheckBox.Checked = true;
            LongPassingCheckBox.Checked = true;
            ShootingCheckBox.Checked = true;
        }

        protected void UnCheckAllAttributes(object sender, EventArgs e)
        {
            InstinctsCheckbox.Checked = false;
            GoalkeepingCheckBox.Checked = false;
            PositioningCheckBox.Checked = false;
            StaminaCheckBox.Checked = false;
            TacklingCheckBox.Checked = false;
            PowerCheckBox.Checked = false;
            HeadingCheckBox.Checked = false;
            QuicknessCheckBox.Checked = false;
            TechniqueCheckBox.Checked = false;
            ShootingCheckBox.Checked = false;
            LongPassingCheckBox.Checked = false;
            ShootingCheckBox.Checked = false;
        }

        private void RefreshTrainingGraph()
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            double minimum = 0, maximum = 0;
            string SeriesName;
            double date;
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {

                #region Bind Data

                TrainingFollowChart.Series.Clear();
                if (InstinctsCheckbox.Checked)
                {
                    SqlCommand cmd1 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd1.CommandType = CommandType.StoredProcedure;
                    cmd1.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd1.Parameters.AddWithValue("Attribute", "1");
                    cmd1.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader1;
                    try
                    {
                        conn.Open();
                        reader1 = cmd1.ExecuteReader();
                        if (reader1.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_Instincts;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader1.Read())
                            {
                                date = reader1.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader1.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }   
                }

                if (GoalkeepingCheckBox.Checked)
                {
                    SqlCommand cmd2 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd2.CommandType = CommandType.StoredProcedure;
                    cmd2.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd2.Parameters.AddWithValue("Attribute", "2");
                    cmd2.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader2;
                    try
                    {
                        conn.Open();
                        reader2 = cmd2.ExecuteReader();
                        if (reader2.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_GoalKeeping;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader2.Read())
                            {
                                date = reader2.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader2.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }
                }
                
                
                if (PositioningCheckBox.Checked)
                {
                    SqlCommand cmd3 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd3.CommandType = CommandType.StoredProcedure;
                    cmd3.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd3.Parameters.AddWithValue("Attribute", "3");
                    cmd3.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader3;
                    try
                    {
                        conn.Open();
                        reader3 = cmd3.ExecuteReader();
                        if (reader3.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_Positioning;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader3.Read())
                            {
                                date = reader3.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader3.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }  
                }
                

                if (StaminaCheckBox.Checked)
                {
                    SqlCommand cmd4 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd4.CommandType = CommandType.StoredProcedure;
                    cmd4.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd4.Parameters.AddWithValue("Attribute", "4");
                    cmd4.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader4;
                    try
                    {
                        conn.Open();
                        reader4 = cmd4.ExecuteReader();
                        if (reader4.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_Stamina;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader4.Read())
                            {
                                date = reader4.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader4.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }  
                }
                
                if (PowerCheckBox.Checked)
                {
                    SqlCommand cmd6 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd6.CommandType = CommandType.StoredProcedure;
                    cmd6.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd6.Parameters.AddWithValue("Attribute", "5");
                    cmd6.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader6;
                    try
                    {
                        conn.Open();
                        reader6 = cmd6.ExecuteReader();
                        if (reader6.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_Power;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader6.Read())
                            {
                                date = reader6.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader6.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }
                }
                

                if (TacklingCheckBox.Checked)
                {
                    SqlCommand cmd5 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd5.CommandType = CommandType.StoredProcedure;
                    cmd5.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd5.Parameters.AddWithValue("Attribute", "6");
                    cmd5.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader5;
                    try
                    {
                        conn.Open();
                        reader5 = cmd5.ExecuteReader();
                        if (reader5.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_Tackling;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader5.Read())
                            {
                                date = reader5.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader5.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }
                }

                if (HeadingCheckBox.Checked)
                {
                    SqlCommand cmd7 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd7.CommandType = CommandType.StoredProcedure;
                    cmd7.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd7.Parameters.AddWithValue("Attribute", "7");
                    cmd7.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader7;
                    try
                    {
                        conn.Open();
                        reader7 = cmd7.ExecuteReader();
                        if (reader7.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_Heading;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader7.Read())
                            {
                                date = reader7.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader7.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }
                }


                if (QuicknessCheckBox.Checked)
                {
                    SqlCommand cmd8 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd8.CommandType = CommandType.StoredProcedure;
                    cmd8.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd8.Parameters.AddWithValue("Attribute", "8");
                    cmd8.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader8;
                    try
                    {
                        conn.Open();
                        reader8 = cmd8.ExecuteReader();
                        if (reader8.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_Quickness;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader8.Read())
                            {
                                date = reader8.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader8.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }
                }



                if (TechniqueCheckBox.Checked)
                {
                    SqlCommand cmd9 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd9.CommandType = CommandType.StoredProcedure;
                    cmd9.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd9.Parameters.AddWithValue("Attribute", "9");
                    cmd9.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader9;
                    try
                    {
                        conn.Open();
                        reader9 = cmd9.ExecuteReader();
                        if (reader9.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_Technique;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader9.Read())
                            {
                                date = reader9.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader9.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }
                }


                if (ShortPassingCheckBox.Checked)
                {
                    SqlCommand cmd10 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd10.CommandType = CommandType.StoredProcedure;
                    cmd10.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd10.Parameters.AddWithValue("Attribute", "10");
                    cmd10.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader10;
                    try
                    {
                        conn.Open();
                        reader10 = cmd10.ExecuteReader();
                        if (reader10.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_ShortPassing;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader10.Read())
                            {
                                date = reader10.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader10.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }
                }

                if (LongPassingCheckBox.Checked)
                {
                    SqlCommand cmd11 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd11.CommandType = CommandType.StoredProcedure;
                    cmd11.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd11.Parameters.AddWithValue("Attribute", "11");
                    cmd11.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader11;
                    try
                    {
                        conn.Open();
                        reader11 = cmd11.ExecuteReader();
                        if (reader11.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_LongPassing;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader11.Read())
                            {
                                date = reader11.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader11.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }
                }


                if (ShootingCheckBox.Checked)
                {
                    SqlCommand cmd12 = new SqlCommand("Nivdal_GetPlayerTrainingProgress", conn);
                    cmd12.CommandType = CommandType.StoredProcedure;
                    cmd12.Parameters.AddWithValue("PlayerId", PlayerIdHiddenField.Value);
                    cmd12.Parameters.AddWithValue("Attribute", "12");
                    cmd12.Parameters.AddWithValue("TeamId", ou.TeamId);
                    SqlDataReader reader12;
                    try
                    {
                        conn.Open();
                        reader12 = cmd12.ExecuteReader();
                        if (reader12.HasRows)
                        {
                            SeriesName = Resources.Resource.Global_Shooting;
                            TrainingFollowChart.Series.Add(SeriesName);
                            TrainingFollowChart.Series[SeriesName].ChartType = SeriesChartType.Line;
                            TrainingFollowChart.Series[SeriesName].BorderWidth = 2;
                            TrainingFollowChart.Series[SeriesName].ShadowOffset = 2;
                            TrainingFollowChart.Series[SeriesName].XValueType = ChartValueType.DateTime;
                            while (reader12.Read())
                            {
                                date = reader12.GetDateTime(0).ToOADate();

                                if ((minimum == 0) || (minimum > date))
                                    minimum = date;
                                if ((maximum == 0) || (maximum < date))
                                    maximum = date;

                                TrainingFollowChart.Series[SeriesName].Points.AddXY(date, reader12.GetDecimal(1));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        conn.Close();
                    }
                }

                #endregion Bind Data

                //Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = minimum;
                //Chart1.ChartAreas["ChartArea1"].AxisX.Maximum = maximum;

                TrainingFollowChart.ChartAreas["ChartArea1"].AxisX.Minimum = minimum;
                TrainingFollowChart.ChartAreas["ChartArea1"].AxisX.Maximum = maximum;
            }
        }

        protected void RecreateGraph(object sender, EventArgs e)
        {
            RefreshTrainingGraph();
        }

        protected void InviteToNT(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            string Answer = GND.ReadNivdalStringData("PlayerId", "NTTeamId", "UserId", "Language",
                                                     "Nivdal_NTInvitePlayerToNationalTeam",
                                                     PlayerIdHiddenField.Value, ou.NationalTeamCoach,
                                                     ou.UserId, ou.Language);
            Response.Redirect("~/Player.aspx?Id=" + PlayerIdHiddenField.Value);
        }

        protected void ReleaseFromNT(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            string Answer = GND.ReadNivdalStringData("PlayerId", "NTTeamId", "UserId", "Language",
                                                     "Nivdal_NTReleasePlayerFromNationalTeam",
                                                     PlayerIdHiddenField.Value, ou.NationalTeamCoach,
                                                     ou.UserId, ou.Language);
            Response.Redirect("~/Player.aspx?Id=" + PlayerIdHiddenField.Value);
        }

        protected void EditPublicNote(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string PublicNote = (FormView1.FindControl("PublicNoteTextBox") as TextBox).Text.Trim();
            string Message = GND.ExecNivdalSQL("PlayerId", "TeamId", "Language", "Note", "Nivdal_UpdatePlayerPublicNote",
                PlayerIdHiddenField.Value, ou.TeamId,ou.Language, PublicNote);
            Response.Redirect("Player.aspx?Id=" + PlayerIdHiddenField.Value + "&Message=" + Message);
        }
    }
}